package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    AdminMapper mapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security " +
                "框架自动调用UserDetailServiceImpl实现类中的loadUserByUsername方法,参数:{}",s);
        AdminLoginInfoVO admin = mapper.getLoginInfoByUsername(s);
        log.debug("从数据库中根据{}查询管理员信息,结果{}",s,admin);
        if (admin==null){
            log.debug("没有与【{}】匹配的用户详情,即将抛出BadCredentialsException",s);
           String message="登录失败,用户名不存在";
           throw new BadCredentialsException(message);
        }
        List<GrantedAuthority> authorities = new ArrayList();
        List<String> permissions = admin.getPermissions();
        for (String permission : permissions) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        AdminDetails adminDetails = new AdminDetails(admin.getId(),
                admin.getUsername(), admin.getPassword(),
                admin.getEnable()==1,authorities);

          /* UserDetails userDetails = User.builder()
                   .username(admin.getUsername())
                   .password(admin.getPassword())
                   .disabled(admin.getEnable() == 0)
                   .accountLocked(false)
                   .accountExpired(false)
                   .credentialsExpired(false)
                   .authorities("暂时给出假的权限标识")
                   .build();*/
        log.debug("即将向Spring Security框架返回UserDetails对象:{}",adminDetails);
           return adminDetails;
       }


}
